# MCP Server工具 - MCP Server 包含多类工具
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("TimeSeries")


@mcp.tool()
def visualize_line_chart(data_num, predict_num) -> str:
    """
    用js的echart代码生成折线图。输入分为两部分:
    1.已有数据，格式为[{"time":..., "value":...}, ...]
    2.预测数据，格式为[{"time":..., "value":...}, ...]
     要把两部分数据画在一张图中,但是用不同颜色表示,并且用不同的图标表示
     图表的标题为"时间序列数据与预测"
     图表的x轴为时间，y轴为指标值

    输入格式说明:
    ============

    参数:
    - data (str): 历史数据的JSON字符串
    - predict_data (str): 预测数据的JSON字符串

    数据格式:
    =========

    历史数据格式 (data):
    [
        {"time": "20240601", "value": 100},
        {"time": "20240602", "value": 120},
        {"time": "20240603", "value": 110}
    ]

    预测数据格式 (predict_data):
    [
        {"time": "20240604", "value": 130},
        {"time": "20240605", "value": 140}
    ]

    字段说明:
    =========
    - time: 时间标识，格式为YYYYMMDD（8位数字），如20240601表示2024年6月1日
    - value: 对应的数值，必须是数字类型

    注意事项:
    =========
    1. 预测数据的时间应该紧接着历史数据的最后一个时间点
    2. 时间格式必须为YYYYMMDD（8位数字）
    3. 数值字段必须是数字类型
    4. 输入必须是有效的JSON字符串

    示例:
    =====
    >>> historical_data = [
    ...     {"time": "20240101", "value": 100},
    ...     {"time": "20240102", "value": 120},
    ...     {"time": "20240103", "value": 110}
    ... ]
    >>> prediction_data = [
    ...     {"time": "20240104", "value": 130},
    ...     {"time": "20240105", "value": 140}
    ... ]
    >>> import json
    >>> data_json = json.dumps(historical_data)
    >>> predict_json = json.dumps(prediction_data)
    >>> result = visualize_line_chart(data_json, predict_json)
    """
    # 用js的echart代码生成折线图
    # 假设data和predict_data均为JSON字符串，格式为[{"time":..., "value":...}, ...]
    import json

    try:
        data_points = json.loads(data)
        predict_points = json.loads(predict_data)
    except Exception as e:
        return f"输入数据格式错误: {e}"

    # 构造x轴和y轴数据
    x_data = [point["time"] for point in data_points] + [point["time"] for point in predict_points if
                                                         point["time"] not in [p["time"] for p in data_points]]

    # 构造已有数据系列
    historical_data = [point["value"] for point in data_points]

    # 构造预测数据系列，从历史数据的最后一个点开始，前面用None填充
    predict_data = [None] * (len(data_points) - 1) + [historical_data[-1]]
    if data_points and predict_points:
        # 从历史数据的最后一个点开始
        for point in predict_points:
            predict_data.append(point["value"])

    # 生成ECharts配置
    echarts_config = {
        "title": {
            "text": "时间序列数据与预测",
            "left": "center",
            "textStyle": {
                "fontSize": 18,
                "fontWeight": "bold"
            }
        },
        "tooltip": {
            "trigger": "axis",
            "axisPointer": {
                "type": "cross"
            }
        },
        "legend": {
            "data": ["已有数据", "预测数据"],
            "top": 30
        },
        "grid": {
            "left": "3%",
            "right": "4%",
            "bottom": "3%",
            "containLabel": True
        },
        "xAxis": {
            "type": "category",
            "data": x_data
        },
        "yAxis": {
            "type": "value",
            "name": "数值"
        },
        "series": [
            {
                "name": "预测数据",
                "type": "line",
                "data": predict_data,
                "itemStyle": {
                    "color": "#EE6666"
                },
                "lineStyle": {
                    "color": "#EE6666",
                    "type": "dashed",
                    "width": 3
                },
                "symbol": "diamond",
                "symbolSize": 8
            },
            {
                "name": "已有数据",
                "type": "line",
                "data": historical_data,
                "itemStyle": {
                    "color": "#5470C6"
                },
                "lineStyle": {
                    "color": "#5470C6",
                    "width": 3
                },
                "symbol": "circle",
                "symbolSize": 6
            }
        ]
    }

    return json.dumps(echarts_config, ensure_ascii=False)


if __name__ == "__main__":
    mcp.run(transport='stdio')  # Run server via stdio
#     # 测试一下函数能否生成网页可视化
#     # 测试 visualize_line_chart 函数能否生成网页可视化代码
#     def test_visualize_line_chart():
#         # 构造模拟数据
#         data_points = [{"time": f"202406{i+1:02d}", "value": i*10+5} for i in range(7)]
#         predict_points = [{"time": f"202406{i+8:02d}", "value": 80 + i*12} for i in range(3)]
#
#         # print(data_points[1]["time"])
#
#         # 转换为JSON字符串
#         import json
#         data_json = json.dumps(data_points)
#         predict_json = json.dumps(predict_points)
#
#         # 调用待测函数
#         if "visualize_line_chart" in globals():
#             echarts_config = visualize_line_chart(data_json, predict_json)
#
#             # 生成完整的HTML页面
#             html_content = f"""
# <!DOCTYPE html>
# <html>
# <head>
#     <meta charset="utf-8">
#     <title>时间序列图表</title>
#     <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
#     <style>
#         body {{
#             font-family: Arial, sans-serif;
#             margin: 20px;
#             background-color: #f5f5f5;
#         }}
#         .container {{
#             max-width: 1200px;
#             margin: 0 auto;
#             background-color: white;
#             padding: 20px;
#             border-radius: 8px;
#             box-shadow: 0 2px 10px rgba(0,0,0,0.1);
#         }}
#         h1 {{
#             color: #333;
#             text-align: center;
#             margin-bottom: 30px;
#         }}
#         #chart {{
#             width: 100%;
#             height: 500px;
#         }}
#         .loading {{
#             text-align: center;
#             padding: 50px;
#             color: #666;
#         }}
#     </style>
# </head>
# <body>
#     <div class="container">
#         <h1>时间序列数据可视化</h1>
#         <div id="chart">
#             <div class="loading">正在加载图表...</div>
#         </div>
#     </div>
#
#     <script>
#         // 等待页面加载完成
#         document.addEventListener('DOMContentLoaded', function() {{
#             // 检查ECharts是否加载成功
#             if (typeof echarts === 'undefined') {{
#                 document.getElementById('chart').innerHTML = '<div class="loading">ECharts库加载失败，请检查网络连接</div>';
#                 return;
#             }}
#
#             try {{
#                 // 初始化图表
#                 var chartDom = document.getElementById('chart');
#                 var myChart = echarts.init(chartDom);
#
#                 var option = {echarts_config};
#
#                 myChart.setOption(option);
#
#                 // 响应式调整
#                 window.addEventListener('resize', function() {{
#                     myChart.resize();
#                 }});
#
#                 console.log('图表加载成功');
#             }} catch (error) {{
#                 console.error('图表初始化失败:', error);
#                 document.getElementById('chart').innerHTML = '<div class="loading">图表初始化失败: ' + error.message + '</div>';
#             }}
#         }});
#     </script>
# </body>
# </html>
#             """
#
#             # 保存HTML到文件
#             import os
#             output_file = "time_series_chart.html"
#             with open(output_file, "w", encoding="utf-8") as f:
#                 f.write(html_content)
#
#             print(f"HTML文件已保存到: {os.path.abspath(output_file)}")
#             print("请在浏览器中打开该文件查看图表")
#
#             # 尝试在默认浏览器中打开
#             import webbrowser
#             try:
#                 webbrowser.open(f"file://{os.path.abspath(output_file)}")
#                 print("已在默认浏览器中打开图表")
#             except Exception as e:
#                 print(f"无法自动打开浏览器: {e}")
#                 print(f"请手动打开文件: {os.path.abspath(output_file)}")
#         else:
#             print("未找到 visualize_line_chart 函数，请检查函数定义。")
#
#     test_visualize_line_chart()
